﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;

namespace UserGroupData
{
    public class PaymentTypeRepository : IPaymentTypeRepository
    {
        public PaymentTypeDTO GetPaymentType(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                var meeting = ctx.PaymentTypes.Where(d => d.Id == id);
                var entity = meeting.FirstOrDefault();
                Mapper.CreateMap<PaymentType, PaymentTypeDTO>();
                var dto = Mapper.Map<PaymentType, PaymentTypeDTO>(entity);
                return dto;
            }
        }

        public List<PaymentTypeDTO> GetAllPaymentTypes()
        {
            using (var ctx = new UserGroupEntities())
            {
                var entities = ctx.PaymentTypes.ToList();
                Mapper.CreateMap<PaymentType, PaymentTypeDTO>();
                var dto = Mapper.Map<List<PaymentType>, List<PaymentTypeDTO>>(entities);
                return dto;
            }
        }

        public int AddNewPaymentType(PaymentTypeDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<PaymentTypeDTO, PaymentType>();
                var entity = Mapper.Map<PaymentTypeDTO, PaymentType>(dto);
                ctx.AddToPaymentTypes(entity);
                ctx.SaveChanges();
                return entity.Id;
            }
        }

        public void UpdatePaymentType(PaymentTypeDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<PaymentTypeDTO, PaymentType>();
                var entity = Mapper.Map<PaymentTypeDTO, PaymentType>(dto);
                ctx.ApplyCurrentValues("PaymentTypes", entity);
                ctx.SaveChanges();
            }
        }

        public void DeletePaymentTypeDTO(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                PaymentType dbDept = ctx.PaymentTypes.First(d => d.Id == id);
                ctx.DeleteObject(dbDept);
                ctx.SaveChanges();
            }
        }
    }
}
